from datetime import timedelta

import sqlalchemy
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship

Base = sqlalchemy.orm.declarative_base()

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    username = Column(String, nullable=False)
    password = Column(String, nullable=False,default="123456")
    name = Column(String, nullable=False)
    power = Column(Integer, nullable=False,default=0)

    # 通过 relationship 反向关联 Worker
    worker = relationship("Worker", back_populates="user")

    def add_user(self,session):

        session.add(self)
        session.commit()

    def __repr__(self):
        return f"<User(id={self.id}, username={self.username}, name={self.name})>"


def array_to_worker_time(array):
    # 验证输入数组是否为正确的形状
    if len(array) != 35 :
        raise ValueError("值班时间格式不正确")

    # # 从二维数组按列转换回字符串
    # result = ""
    # for col in range(7):  # 遍历列
    #     for row in array:  # 遍历行以获取当前列的字符
    #         result += row[col]

    result = ""
    for i in array:
        result += str(i)

    # print(result)
    # worker = Worker(work_time=result)
    # print(worker.get_worker_time_array())
    return result


class Worker(Base):
    __tablename__ = 'worker'
    id = Column(Integer, primary_key=True)
    stu_id = Column(String,ForeignKey('user.username'))
    name = Column(String, nullable=False)
    work_time = Column(String, nullable=False,default="00000"+"00000"+"00000"+"00000"+"00000"+"00000"+"00000")
    grade = Column(Integer,nullable=False,default=0)
    status = Column(Integer,nullable=False,default=1)

    # 通过 relationship 反向关联 User
    user = relationship("User", back_populates="worker")
    document = relationship("Document", back_populates="worker")

    # 获取值班信息的二维数组
    # def get_worker_time_array(self):
    #     if len(self.work_time) != 35:
    #         self.work_time = self.work_time.ljust(35,'0')
    #
    #     # 转换为字符列表
    #     char_list = list(self.work_time)
    #
    #     rows = 5
    #     cols = 7
    #     # 按列读取字符，构建成二维数组
    #     result = [[char_list[j + i * cols] for j in range(cols)] for i in range(rows)]
    #
    #     return result

    # 值班时间转换成数组
    def get_worker_time_array(self):
        if len(self.work_time) != 35:
            self.work_time = self.work_time.ljust(35,'0')

        # 转换为01数组
        char_list = []
        for s in self.work_time:
            char_list.append(int(s))

        return char_list

    def __repr__(self):
        return f"<Worker(stu_id={self.stu_id}, name={self.name})>"

class Document(Base):
    __tablename__ = 'document'
    id = Column(Integer, primary_key=True)
    path = Column(String, nullable=False)
    contributor = Column(String, ForeignKey('worker.stu_id'))
    title = Column(String, nullable=False)
    description = Column(String)

    # 通过 relationship 反向关联 Worker
    worker = relationship("Worker", back_populates="document")

    def __repr__(self):
        return f"<Document(id={self.id}, path={self.path})>"

class Turn(Base):
    __tablename__ = 'turn'
    id = Column(Integer, primary_key=True)
    start = Column(String, nullable=False)
    end = Column(String, nullable=False)
    week = Column(Integer, nullable=False)


def id_to_name(stu_id,session):
    if not stu_id:
        return "无"

    worker = session.query(Worker).filter_by(stu_id=stu_id).first()
    if not worker:
        return "已离职"

    return worker.name


class Schedule(Base):
    __tablename__ = "term_schedule"
    id = Column(Integer, primary_key=True)
    s1_1 = Column(String)
    s1_2 = Column(String)
    s1_3 = Column(String)
    s1_4 = Column(String)
    s2_1 = Column(String)
    s2_2 = Column(String)
    s2_3 = Column(String)
    s2_4 = Column(String)
    s3_1 = Column(String)
    s3_2 = Column(String)
    s3_3 = Column(String)
    s3_4 = Column(String)
    s3_5 = Column(String)
    s3_6 = Column(String)
    s4_1 = Column(String)
    s4_2 = Column(String)
    s4_3 = Column(String)
    s4_4 = Column(String)
    s4_5 = Column(String)
    s4_6 = Column(String)
    s5_1 = Column(String)
    s5_2 = Column(String)
    s5_3 = Column(String)
    s5_4 = Column(String)
    day = Column(Integer)
    week = Column(Integer)
    status = Column(Integer)

    def __repr__(self):
        return f"<Schedule(id={self.id}, dat={self.day},week={self.week})>"

def get_week_of_month(dt):
    """
    返回给定日期是所在月的第几周
    这里我们定义每月的第一天所在的周为第一周
    """
    # 获取当月第一天
    first_day = dt.replace(day=1)
    # 计算第一天是星期几（0代表星期一，6代表星期日）
    weekday_of_first_day = first_day.weekday()
    # 计算第一周的起始日期（即当月第一个星期一的日期）
    # 如果第一天就是星期一，则直接是第一周的开始
    # 否则，需要减去第一天到第一个星期一的天数
    if weekday_of_first_day != 0:
        # 第一个星期一的日期
        first_monday = first_day + timedelta(days=7-weekday_of_first_day)
    else:
        first_monday = first_day

        # 计算给定日期是第一个星期一之后的第几周
    # 转换为从第一个星期一开始的日期，然后除以7取整加1
    days_passed = (dt - first_monday).days
    week_number = (days_passed // 7) + 1

    return week_number

def is_second_week_of_month(dt):
    """
    判断给定日期是否是所在月的第二个周
    """
    week_number = get_week_of_month(dt)
    return week_number == 2



def load_schedules_stu(schedules,record,session):
    # 字典转换星期
    dict_day = {
        1:"mon",
        2:"tue",
        3:"wed",
        4:"thu",
        5:"fri",
        6:"sat",
        7:"sun"
    }

    # 时间段
    periods = [
        ("one", ["s1_1", "s1_2", "s1_3", "s1_4"]),
        ("two", ["s2_1", "s2_2", "s2_3", "s2_4"]),
        ("three", ["s3_1", "s3_2", "s3_3", "s3_4", "s3_5", "s3_6"]),
        ("four", ["s4_1", "s4_2", "s4_3", "s4_4", "s4_5", "s4_6"]),
        ("five",["s5_1", "s5_2", "s5_3", "s5_4"])
    ]

    for schedule in schedules:
        day_key = dict_day.get(schedule.day)
        if day_key is None:
            continue  # 如果day_key是None，则跳过这个循环的剩余部分

        for period_name, field_prefixes in periods:
            if period_name not in record[day_key]:
                record[day_key][period_name] = []  # 确保列表存在

            for field_prefix in field_prefixes:
                field_name = f"{field_prefix}"
                # 假设schedule对象有动态属性，如s1_1, s1_2等
                record[day_key][period_name].append(id_to_name(getattr(schedule, field_name), session))

    # 传统
    # for schedule in schedules:
    #     record[dict_day.get(schedule.day)]["one"].append(id_to_name(schedule.s1_1,session))
    #     record[dict_day.get(schedule.day)]["one"].append(id_to_name(schedule.s1_2,session))
    #     record[dict_day.get(schedule.day)]["one"].append(id_to_name(schedule.s1_3,session))
    #     record[dict_day.get(schedule.day)]["one"].append(id_to_name(schedule.s1_4,session))
    #
    #     record[dict_day.get(schedule.day)]["two"].append(id_to_name(schedule.s2_1,session))
    #     record[dict_day.get(schedule.day)]["two"].append(id_to_name(schedule.s2_2,session))
    #     record[dict_day.get(schedule.day)]["two"].append(id_to_name(schedule.s2_3,session))
    #     record[dict_day.get(schedule.day)]["two"].append(id_to_name(schedule.s2_4,session))
    #
    #     record[dict_day.get(schedule.day)]["three"].append(id_to_name(schedule.s3_1,session))
    #     record[dict_day.get(schedule.day)]["three"].append(id_to_name(schedule.s3_2,session))
    #     record[dict_day.get(schedule.day)]["three"].append(id_to_name(schedule.s3_3,session))
    #     record[dict_day.get(schedule.day)]["three"].append(id_to_name(schedule.s3_4,session))
    #     record[dict_day.get(schedule.day)]["three"].append(id_to_name(schedule.s3_5,session))
    #     record[dict_day.get(schedule.day)]["three"].append(id_to_name(schedule.s3_6,session))
    #
    #     record[dict_day.get(schedule.day)]["four"].append(id_to_name(schedule.s4_1,session))
    #     record[dict_day.get(schedule.day)]["four"].append(id_to_name(schedule.s4_2,session))
    #     record[dict_day.get(schedule.day)]["four"].append(id_to_name(schedule.s4_3,session))
    #     record[dict_day.get(schedule.day)]["four"].append(id_to_name(schedule.s4_4,session))
    #     record[dict_day.get(schedule.day)]["four"].append(id_to_name(schedule.s4_5,session))
    #     record[dict_day.get(schedule.day)]["four"].append(id_to_name(schedule.s4_6,session))
    #
    #     record[dict_day.get(schedule.day)]["five"].append(id_to_name(schedule.s5_1,session))
    #     record[dict_day.get(schedule.day)]["five"].append(id_to_name(schedule.s5_2,session))
    #     record[dict_day.get(schedule.day)]["five"].append(id_to_name(schedule.s5_3,session))
    #     record[dict_day.get(schedule.day)]["five"].append(id_to_name(schedule.s5_4,session))

    return record
